package cn.gcjxsc.payment.service.wx;

import cn.gcjxsc.common.consts.OrderDiscr;
import cn.gcjxsc.common.consts.PayStatus;
import cn.gcjxsc.common.data.notify.order.ResultHandleData;
import cn.gcjxsc.payment.data.WeChatConfig;
import cn.gcjxsc.payment.data.wx.xml.PayResult;
import cn.gcjxsc.payment.entity.wx.PayRecord;
import cn.gcjxsc.payment.messaging.source.PaymentHandleSource;
import cn.gcjxsc.payment.util.WxUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * @author pumbaa
 * @since 1.0
 */
@Service
public class PayResultService {
    private Logger logger = LoggerFactory.getLogger(PayResultService.class);
    @Autowired
    private PayRecordService payRecordService;
    @Autowired
    private PaymentHandleSource source;

    /**
     * 获得微信回调数据
     *
     * @param request
     * @return
     */
    public String getXmlFromRequest(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();
        String input;
        try {
            while ((input = request.getReader().readLine()) != null) {
                sb.append(input);
            }
            request.getReader().close();
        } catch (IOException e) {
            logger.error("读取微信回调出错.{}", e.getMessage());
            return null;
        }
        return sb.toString();
    }

    /**
     * 检验签名
     *
     * @param data   回调数据
     * @param config 配置文件
     * @return
     */
    public boolean verifySign(Map<String, String> data, WeChatConfig config) {
        String signature = WxUtil.generateSignature(data, config.getPay_key());
        return signature.equals(data.get("sign"));
    }

    /**
     * 是否支付成功
     *
     * @param result 回调结果
     * @return
     */
    public boolean isPaySuccess(PayResult result) {
        return result.getReturn_code().equals(WxUtil.SUCCESS) && result.getResult_code().equals(WxUtil.SUCCESS);
    }

    public void processPayResult(PayResult payResult, PayRecord payRecord) {
        payRecord.setTradeTime(System.currentTimeMillis() / 1000);
        if (!isPaySuccess(payResult)) {
            payRecord.setStatus(PayStatus.INVALID.ordinal());
        } else {
            payRecord.setStatus(PayStatus.PAID.ordinal());
            payRecord.setOutTradeNo(payResult.getTransaction_id());
        }
    }

    public void handle(ResultHandleData data) {
        String discr = data.getDiscr();
        logger.info("discr:, {}", discr);
        if (discr.equalsIgnoreCase(OrderDiscr.RECHARGE_ORDER.toString())) {
            //商户充值订单
            source.sendRechargeHandleMessage(data);
        } else if (discr.equalsIgnoreCase(OrderDiscr.SHOPPING_ORDER.toString())) {
            //购物订单
            source.sendShoppingHandleMessage(data);
        }
    }
}
